const fs = require('fs').promises
const path = require("path")

/**
 * 根据传入的名称获取绝对路径
 * @param name
 * @returns {string}
 */
function generateAbsDirPath(name) {
    return path.resolve(__dirname, name)
}

/**
 * 获取文件夹大小的方法
 * @param absPath
 * @returns {Promise<unknown>}
 */
async function getSize(absPath) {
    const pathMsg = await fs.stat(absPath)
    const isFile = pathMsg.isFile()
    if (isFile) {
        return pathMsg.size
    }
    return (await Promise.all((await fs.readdir(absPath))
        .map(ele => getSize(path.join(absPath, ele)))))
        .reduce((pre, cur, index) => pre + cur, 0)
}


const dirAbsPath1 = generateAbsDirPath("") //根目录
const dirAbsPath2 = generateAbsDirPath("www") //www目录
const dirAbsPath3 = generateAbsDirPath("index.js") //index.js
/**
 * 执行函数
 * @returns {Promise<void>}
 */
async function run() {
    const sumSize1 = await getSize(dirAbsPath1)
    const sumSize2 = await getSize(dirAbsPath2)
    const sumSize3 = await getSize(dirAbsPath3)
    console.log("根目录大小 =", sumSize1)
    console.log("www目录大小 =", sumSize2)
    console.log("index.js大小 =", sumSize3)
}

run()